import { join, resolve } from "node:path"
import fs from "node:fs"

export const getArgs = () => process.argv.slice(2)

// 获取当前工作目录的路径与传参的合并路径
export const getPathFromExecRoot = (path: string = ".") => join(process.cwd(), path)

// 复制文件/文件夹
export const copyFile = (src: string, dest: string) => fs.statSync(src).isDirectory() ? copyDir(src, dest) : fs.copyFileSync(src, dest)
export type Obj<T = any> = Record<string, T>
export const filterItem = (arr: any[], filterArr: any[]) => arr.filter(v => (!filterArr.includes(v)))
export const filterRename = (str: string, filter: string[], rules: Obj<string>) => {
  if (filter.includes(str)) Object.keys(rules).forEach(key => str = str.replace(key, rules[key]))
  return str
}
export const copyDir = (srcDir: string, destDir: string, renameRule: [string[], Obj<string>] = [[], {}], exclude?: string[]) => {
  // 1 创建目录
  fs.mkdirSync(destDir, { recursive: true })
  // 2 循环复制
  const dirs = fs.readdirSync(srcDir)
  const FileArr = filterItem(dirs, [".git"])
  // 3 循环目录
  for (let fileName of FileArr) {
    if (exclude?.includes(fileName)) continue;
    const destFileName = filterRename(fileName, ...renameRule)
    const srcFile = resolve(srcDir, fileName)
    const destFile = resolve(destDir, destFileName)
    copyFile(srcFile, destFile)
  }
}